

import Canceler from './canceler'
import { RequestOptions, ResponseBody } from './types'
import { Request as Http } from './http'
import { queue } from './queue'


import {
  APP_CODE_KEY,
  AUTH_TICKET_KEY,
  CLIENT_CHANNEL,
  HOS_CODE_KEY,
  R_A_TOKEN,
  USER_TICKET_KEY
} from '../../../../weapp/miniprogram/constants/key'

export enum ResCode {
  CANCEL = -1,
  SUCCESS = 0,
  INVALID_TOKEN = 301,
  /**
   * 订单不存在
   */
  ORDER_NOT_EXISTS = 4001,
  COMMON_ALERT = 9001,
  COMMON_ERROR = 10000,
  /**
   * 未进行小程序openid授权
   */
  UN_AUTH = 4001,
  /**
   * 未登录
   */
  UN_LOGIN = 103,

  /**
   * 订单信息缺失
   */
  ADDRESS_DEFECT_INFO = 4201,
  /**
   * 住院预约HIS提示
   */
  HIS_APPOINTMENT_CONFIRM = 6001,
}

export const Request = new Http({
  config: {
    headers: {
      'Content-Type': 'application/json;charset=UTF-8'
    },
    timeout: 10000,
    errorTips: true,
    baseURL: 'https://api.zhiyax.cn/',
    uploadURL: 'https://api.zhiyax.cn/'
  },
  requestInterceptor: (config) => {
    //TODO配置header内所需的其他东西
    // config.headers[APP_CODE_KEY] = `${process.env.EF_APP_CODE}`
    //
    return config
  },

  async responseCallback<T>(response: ResponseBody<T>, resolve: (value: T | PromiseLike<T>) => void, reject: (reason?: any) => void, opts: RequestOptions) {
    const { code, data, message } = response
    switch (code) {
      case ResCode.SUCCESS:
        resolve(data)
        break
      case ResCode.UN_AUTH:
        queue.add(opts, resolve, reject)
        if (!queue.isPending) {
          queue.isPending = true
          const res = await getUserTTicket()
          if (res && res.code) {
            queue.isPending = false
            queue.exec()
          }
        }
        break

      case ResCode.INVALID_TOKEN:
        queue.add(opts, resolve, reject)
        if (!queue.isPending) {
          queue.isPending = true
          const res = await refreshToken(data)
          if (res) {
            queue.isPending = false
            queue.exec()
          }
        }
        break

      case ResCode.UN_LOGIN:
        Canceler.removeAll()
        wx.removeStorageSync(USER_TICKET_KEY)
        //TODO 跳转登录
        break
      case ResCode.CANCEL:
        reject({})
        break
      default:
        reject(response)
    }

    if (!opts.errorTips || !message) {
      return
    }

    if (code === ResCode.COMMON_ERROR) {
      const duration = Math.floor(message.length / 5) * 1000
      Toast({ message, duration: duration > 2000 ? duration : 2000 })
    } else if (code === ResCode.COMMON_ALERT) {
      Dialog({
        message,
        confirmButtonText: '知道了'
      })
    }
  }
})
